package com.zzzzzz.topic.dao;

import java.util.List;

import org.bson.types.ObjectId;
import org.springframework.stereotype.Repository;

import com.google.code.morphia.query.Query;
import com.zzzzzz.common.util.StringPool;
import com.zzzzzz.core.dao.morphia.BaseDao;
import com.zzzzzz.core.exception.NoSuchTopicException;
import com.zzzzzz.topic.model.Topic;

@Repository
public class TopicDao extends BaseDao {
	
	private static final String _NO_SUCH_ENTITY_WITH_PRIMARY_KEY = "No Topic exists with the primary key ";

	public void add(Topic topic) {
		datastore.save(topic);
	}

	public void edit(Topic topic) {
		Query<Topic> query = datastore.createQuery(Topic.class);
		query.filter("_id", ObjectId.massageToObjectId(topic.getTopicId()));
		datastore.update(query, datastore.createUpdateOperations(Topic.class)
				.set("title", topic.getTitle())
				.set("content", topic.getContent())
				.set("updDt", topic.getUpdDt())
		);
	}
	
	public void editStatus(String topicId, Integer status) {
		Query<Topic> query = datastore.createQuery(Topic.class);
		query.filter("_id", ObjectId.massageToObjectId(topicId));
		datastore.update(query, datastore.createUpdateOperations(Topic.class).set("status", status));
	}

	public Topic findById(String topicId) throws NoSuchTopicException {
		Topic topic = datastore.find(Topic.class, "_id", ObjectId.massageToObjectId(topicId)).get();
		if(topic == null) {
			throw new NoSuchTopicException(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY + topicId);
		}
		return topic;
	}
	
	public List<Topic> findByCategoryId(String categoryId, int start, int offset, boolean ascending) {
		Query<Topic> query = datastore.createQuery(Topic.class).retrievedFields(true, "title", "content");
		query.filter("categoryId", categoryId).filter("status", 0);
		String condition = "addDt";
		if(!ascending) {
			condition = StringPool.DASH + condition;
		}
		query.limit(offset).offset(start).order(condition);
		return query.asList();
	}
	
	public long findByCategoryIdCount(String categoryId) {
		Query<Topic> query = datastore.createQuery(Topic.class);
		query.filter("categoryId", categoryId).filter("status", 0);
		return datastore.getCount(query);
	}
	
}
